package com.chiaching.chaoxingsecondkill.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.util.*;

@Component
@Slf4j
public class DingUtil {

    private static LinkedHashSet<String> hashSet=new LinkedHashSet<>();

    public static LinkedHashSet<String> getHashSet() {
        return hashSet;
    }

    public static void sendMsg(String text) {
        try {
            if (StrUtil.isBlank(text)) {
                return;
            }
            int hashCode = text.hashCode();
            if (hashSet.contains(String.valueOf(hashCode))){
                log.info("频繁发送! [{}]",text);
                return;
            }else {
                hashSet.add(String.valueOf(hashCode));
            }
            //群机器人复制到的秘钥secret
            String secret = "SEC55105ca6c5bcc2b1b2b335253815f2a1dc6d83f484727cfa05f765b5d5bcc706";
            //获取系统时间戳
            Long timestamp = System.currentTimeMillis();
            //拼接
            String stringToSign = timestamp + "\n" + secret;
            //使用HmacSHA256算法计算签名
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            //进行Base64 encode 得到最后的sign，可以拼接进url里
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
            //钉钉机器人地址（配置机器人的webhook）
            String dingUrl = "https://oapi.dingtalk.com/robot/send?access_token=559e8659aaa1675ac66a0c2697d8d06d9cae4f2b5e92a4d46f82154577c0a8ed&timestamp=" + timestamp + "&sign=" + sign;
            //是否通知所有人
            boolean isAtAll = true;
            //通知具体人的手机号码列表
            List<String> mobileList = new ArrayList<>();
            //钉钉机器人消息内容
            String content = text + "  time: " + DateUtil.formatDateTime(new Date()) + " by chiaching";
            //组装请求内容
            String reqStr = buildReqStr(content, isAtAll, mobileList);
            //推送消息（http请求）
            String result = HttpUtil.post(dingUrl, reqStr);
            System.out.println("result == " + result);
        } catch (Exception e) {
            log.error("发送钉钉消息异常[{}]", text, e);
        }
    }

    /**
     * 组装请求报文
     *
     * @param content
     * @return
     */
    private static String buildReqStr(String content, boolean isAtAll, List<String> mobileList) {
        //消息内容
        Map<String, String> contentMap = new HashMap<>(8);
        contentMap.put("content", content);
        //通知人
        Map<String, Object> atMap = new HashMap<>(8);
        //1.是否通知所有人
        atMap.put("isAtAll", isAtAll);
        //2.通知具体人的手机号码列表
        atMap.put("atMobiles", mobileList);

        Map<String, Object> reqMap = new HashMap<>(8);
        reqMap.put("msgtype", "text");
        reqMap.put("text", contentMap);
        reqMap.put("at", atMap);

        return JSONObject.toJSONString(reqMap);
    }

}
